package com.alibaba.org.service.impl;


import com.alibaba.basic.service.impl.BaseServiceImpl;
import com.alibaba.basic.util.MD5Utils;
import com.alibaba.basic.util.StrUtils;
import com.alibaba.org.domain.Employee;
import com.alibaba.org.mapper.EmployeeMapper;
import com.alibaba.org.service.IEmployeeService;
import com.alibaba.user.domain.Logininfo;
import com.alibaba.user.mapper.LogininfoMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


/**
 * 业务实现类：员工
 */
@Service
public class EmployeeServiceImpl extends BaseServiceImpl<Employee> implements IEmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private LogininfoMapper logininfoMapper;

    @Override
    public void add(Employee employee) {
        //添加logininfo对象
        String salt = StrUtils.getComplexRandomString(32);
        String md5Pwd = MD5Utils.encrypByMd5(employee.getPassword() + salt);
        employee.setSalt(salt);
        employee.setPassword(md5Pwd);
        Logininfo logininfo = employee2Logininfo(employee);
        logininfoMapper.save(logininfo);

        //添加employee
        employee.setLogininfo_id(logininfo.getId());
        super.add(employee);

        //如果添加时选了角色
        if(employee.getRole_id()!=null){
            employeeMapper.addEmployeeRole(employee.getId(),employee.getRole_id());
        }
    }

    private Logininfo employee2Logininfo(Employee employee) {
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(employee,logininfo);
        logininfo.setType(0);
        return logininfo;
    }

    @Override
    public void del(Long id) {

        //删除中间表数据
        employeeMapper.delEmployeeRole(id);

        //删除登录信息id
        Employee employee = employeeMapper.loadById(id);
        logininfoMapper.remove(employee.getLogininfo_id());

        //删除员工信息
        super.del(id);
    }

    @Override
    public void update(Employee employee) {
        //为了获取以前的logininfoId
        Employee oldEmployee = employeeMapper.loadById(employee.getId());

        //处理用户名和密码
        //先修改中间表数据
        String salt = StrUtils.getComplexRandomString(32);
        String md5Pwd = MD5Utils.encrypByMd5(employee.getPassword() + salt);
        employee.setSalt(salt);
        employee.setPassword(md5Pwd);
        Logininfo logininfo = employee2Logininfo(employee);
        logininfo.setId(oldEmployee.getLogininfo_id());
        logininfoMapper.update(logininfo);

        //删除中间表数据
        employeeMapper.delEmployeeRole(employee.getId());
        //选了角色
        if(employee.getRole_id()!=null){
            employeeMapper.addEmployeeRole(employee.getId(),employee.getRole_id());
        }

        //修改员工信息
        super.update(employee);
    }

    //批量删除
    @Override
    public void atchDelete(Long[] ids) {
        for (Long id : ids) {
            del(id);
        }
    }
}
